<template>
  <div class="bg">
    <div class="login-box">
      <h3>叩丁狼商品管理系统</h3>
      <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="0" class="demo-ruleForm">
        <el-form-item prop="username">
          <el-input v-model="ruleForm.username" autocomplete="off">
            <template #prefix>
              <el-icon>
                <User />
              </el-icon>
            </template></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="ruleForm.password" type="password" autocomplete="off">
            <template #prefix><el-icon>
                <Lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
  
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { loginApi } from '@/api'
import { useRouter } from 'vue-router'
const router = useRouter();

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  username: '',
  password: '',
})
const validatePass = (rule: any, value: any, callback: any) => {
  // 校验 密码 有大写、小写、数字
  if (/[A-Z]/.test(value) && /[a-z]/.test(value) && /\d/.test(value)) {
    callback(); // 调用callback放行，校验通过
  } else {
    callback(new Error('密码必须要有大写、小写、数字'))
  }
}
const rules = reactive<FormRules<typeof ruleForm>>({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' },
  { min: 3, max: 10, message: '密码长度应该在3~10位', trigger: 'blur' },
    // { validator: validatePass, trigger: 'blur' }
  ],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      // 校验成功
      // 发请求
      loginApi(ruleForm).then(res => {
        if (res.code === 200) {
          // 登录成功
          // 提示
          ElMessage({
            message: '登录成功',
            type: 'success',
          })
          // 存token
          // 在 token 前面 带上 tokenHead 是一个约定，需要跟后端沟通好
          localStorage.setItem('token', res.data.tokenHead + ' ' + res.data.token)
          // 跳转
          router.push('/home')
        }
      })
    } else {
      // 校验失败
      // 当return false，会自动对表单进行提示
      return false
    }
  })
}
</script>
  
<style lang="less" scoped>
.bg {
  background-color: #2d3a4b;
  min-height: 100vh;

  .login-box {
    width: 400px;
    margin: auto;
    padding-top: 200px;

    h3 {
      color: #fff;
      text-align: center;
    }

    .el-button--primary {
      width: 100%;
    }
  }
}
</style>